import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { postPromptOptimize } from '@/api/3D-Generator/index'

/**
 * 智能优化功能的Composable
 * 封装了智能优化的所有逻辑，包括开关控制、防抖处理、API调用等
 */
export function useSmartOptimization() {
    // ========== 状态管理 ==========

    // 手动优化状态
    const isOptimizing = ref(false)

    // 智能优化状态管理
    const smartOptimization = ref({
        enabled: false,  // 智能优化开关
        loading: false,  // 加载状态
        debounceTimer: null  // 防抖定时器
    })

    // 智能建议状态管理
    const smartSuggestion = ref({
        visible: false,  // 是否显示建议
        data: null,      // AI返回的数据
        lastPrompt: ''   // 上次的提示词，防止重复请求
    })

    // ========== 核心方法 ==========

    /**
     * 智能优化开关切换
     * @param {boolean} enabled - 是否开启智能优化
     * @param {string} currentPrompt - 当前提示词内容
     */
    const onSmartOptimizationToggle = (enabled, currentPrompt = '') => {
        smartOptimization.value.enabled = enabled

        if (!enabled) {
            // 关闭时清理定时器和建议
            clearTimeout(smartOptimization.value.debounceTimer)
            smartSuggestion.value.visible = false
            smartSuggestion.value.data = null
            smartOptimization.value.loading = false
        } else {
            // 开启时立即检查当前输入
            if (currentPrompt.trim()) {
                debouncedOptimize(currentPrompt)
            }
        }
    }

    /**
     * 提示词输入处理
     * @param {string} value - 输入的提示词
     */
    const onPromptInput = (value) => {
        // 如果智能优化开启，进行防抖优化
        if (smartOptimization.value.enabled && value.trim()) {
            debouncedOptimize(value)
        }
    }

    /**
     * 防抖优化函数
     * @param {string} prompt - 需要优化的提示词
     * @param {number} delay - 防抖延迟时间（毫秒）
     */
    const debouncedOptimize = (prompt, delay = 1000) => {
        // 清除之前的定时器
        clearTimeout(smartOptimization.value.debounceTimer)

        // 如果与上次相同，不重复请求
        if (prompt === smartSuggestion.value.lastPrompt) {
            return
        }

        // 设置加载状态
        smartOptimization.value.loading = true

        // 设置防抖定时器
        smartOptimization.value.debounceTimer = setTimeout(async () => {
            try {
                await getSmartSuggestion(prompt)
            } catch (error) {
                console.error('智能优化失败:', error)
            } finally {
                smartOptimization.value.loading = false
            }
        }, delay)
    }

    /**
     * 获取智能建议
     * @param {string} prompt - 提示词
     */
    const getSmartSuggestion = async (prompt) => {
        try {
            console.log('获取智能建议:', prompt)

            // 调用API
            const response = await postPromptOptimize(prompt)
            console.log('智能建议响应:', response)

            // 解析响应数据
            const data = typeof response === 'string' ? JSON.parse(response) : response

            // 更新状态
            smartSuggestion.value.data = data
            smartSuggestion.value.lastPrompt = prompt
            smartSuggestion.value.visible = true

        } catch (error) {
            console.error('获取智能建议失败:', error)
            // 不显示错误消息，避免干扰用户体验
        }
    }

    /**
     * 手动智能优化
     * @param {string} prompt - 当前提示词
     * @returns {Promise<string|null>} - 优化后的提示词，失败返回null
     */
    const handleOptimizePrompt = async (prompt) => {
        if (!prompt.trim()) {
            ElMessage.warning('请先输入描述内容')
            return null
        }

        try {
            isOptimizing.value = true

            const response = await postPromptOptimize(prompt)
            const data = typeof response === 'string' ? JSON.parse(response) : response

            if (data.success && data.prompt) {
                ElMessage.success('提示词已智能优化')
                return data.prompt
            } else {
                ElMessage.info('暂无优化建议')
                return null
            }

        } catch (error) {
            console.error('优化提示词失败:', error)
            ElMessage.error('优化失败，请重试')
            return null
        } finally {
            isOptimizing.value = false
        }
    }

    /**
     * 接受优化后的提示词
     * @returns {string|null} - 优化后的提示词
     */
    const acceptOptimizedPrompt = () => {
        if (smartSuggestion.value.data && smartSuggestion.value.data.prompt) {
            const optimizedPrompt = smartSuggestion.value.data.prompt

            // 隐藏建议
            smartSuggestion.value.visible = false
            smartSuggestion.value.data = null

            ElMessage.success('已应用优化建议')
            return optimizedPrompt
        }
        return null
    }

    /**
     * 忽略建议
     */
    const dismissSuggestion = () => {
        smartSuggestion.value.visible = false
        smartSuggestion.value.data = null

        // 自动关闭智能优化开关
        smartOptimization.value.enabled = false

        // 清理定时器
        clearTimeout(smartOptimization.value.debounceTimer)
        smartOptimization.value.loading = false
    }

    /**
     * 清理所有定时器和状态
     */
    const cleanup = () => {
        clearTimeout(smartOptimization.value.debounceTimer)
        smartOptimization.value.loading = false
        smartSuggestion.value.visible = false
        smartSuggestion.value.data = null
    }

    // ========== 返回接口 ==========
    return {
        // 状态
        isOptimizing,
        smartOptimization,
        smartSuggestion,

        // 方法
        onSmartOptimizationToggle,
        onPromptInput,
        handleOptimizePrompt,
        acceptOptimizedPrompt,
        dismissSuggestion,
        debouncedOptimize,
        cleanup
    }
}